<template>
  <div id="finan">
      <!--搜索框-->
      <div class="interview-header">
          <el-form ref="searchItem" :model="searchItem" :inline="true"  class="demo-form-inline">
              <el-form-item label="订单编号" class="search-item" prop="loanNo">
                  <el-input v-model="searchItem.loanNo" placeholder="订单编号"></el-input>
              </el-form-item>
              <el-form-item label="用户手机号" class="search-item" prop="phone">
                  <el-input v-model="searchItem.phone" placeholder="用户手机号"></el-input>
              </el-form-item>
              <el-form-item label="借款人" class="search-item" prop="realName">
                  <el-input v-model="searchItem.realName" placeholder="借款人"></el-input>
              </el-form-item>
              <el-form-item label="财务状态" prop="auditStatus">
                  <el-select  v-model="searchItem.auditStatus" placeholder="财务核算状态">
                      <el-option label="全部" value=""></el-option>
                      <el-option label="未核算" value="0"></el-option>
                      <el-option label="已核算" value="1"></el-option>
                  </el-select>
              </el-form-item>
              <el-form-item>
                  <el-button type="primary" icon="fa-search" @click="listLoanAudit">查询</el-button>
              </el-form-item>
              <el-form-item>
                  <el-button icon="fa-repeat" @click="resetForm">重置</el-button>
              </el-form-item>
          </el-form>
      </div>

      <!--表格-->
      <div class="table-box">
          <el-table border :data="tableData" tooltip-effect="dark">
              <el-table-column type="index" align="center" label="序号" width="70"></el-table-column>
              <el-table-column prop="auditStatus" align="center" label="状态"></el-table-column>
              <el-table-column prop="createTime" align="center" label="申请时间" width="190"></el-table-column>
              <el-table-column prop="loanNo" align="center" label="订单编号" width="200">
                <template scope="scope">
                    <router-link :to="{path: '/apply/borrowerDetails', query: {loanNo: scope.row.loanNo, userNo: scope.row.userNo}}" style="color: #20a0ff">{{scope.row.loanNo}}</router-link>
                </template>
              </el-table-column>
              <el-table-column prop="realName" align="center" label="借款人" width="110"></el-table-column>
              <el-table-column prop="idcard" align="center" label="身份证号码" width="200"></el-table-column>
              <el-table-column prop="phone" align="center" label="手机号" width="130"></el-table-column>
              <el-table-column prop="carType" align="center" label="车型" width="150"></el-table-column>
              <el-table-column prop="carRemark" align="center" label="说明" width="150" show-overflow-tooltip></el-table-column>
              <el-table-column prop="loanAmount" align="center" label="申请额度（元）" width="140"></el-table-column>
              <el-table-column prop="loanTime" align="center" label="申请期限" width="100"></el-table-column>
              <el-table-column prop="salesman" align="center" label="业务员" width="150"></el-table-column>
              <el-table-column prop="signTime" align="center" label="面签时间" width="190"></el-table-column>
              <el-table-column prop="signUser" align="center" label="面签人" width="150"></el-table-column>
              <el-table-column prop="signAmount" align="center" label="面签额度（元）" width="140"></el-table-column>
              <el-table-column prop="signLoanTime" align="center" label="借款期限" width="100"></el-table-column>
              <el-table-column prop="signInterestRate" align="center" label="利率（%）" width="140"></el-table-column>
              <el-table-column prop="signFee" align="center" label="综合服务费（元）" width="160"></el-table-column>
              <el-table-column prop="signRepayType" align="center" label="还款方式" width="100"></el-table-column>
              <el-table-column prop="signRemark" align="center" label="面签说明" width="150" show-overflow-tooltip></el-table-column>
              <el-table-column align="center" label="风控初审时间" prop="riskTime" width="170"></el-table-column>
              <el-table-column align="center" label="风控初审人员" prop="riskUser" width="140"></el-table-column>
              <el-table-column align="center" label="风控初审额度（元）" prop="riskAmount" width="180"></el-table-column>
              <el-table-column align="center" label="风控初审借款期限" prop="riskLoanTime" width="180"></el-table-column>
              <el-table-column align="center" label="风控初审利率（%）" prop="riskInterestRate" width="180"></el-table-column>
              <el-table-column align="center" label="风控初审综合服务费（元）" prop="riskFee" width="240"></el-table-column>
              <el-table-column align="center" label="风控初审还款方式" prop="riskRepayType" width="160"></el-table-column>
              <el-table-column align="center" label="风控初审说明" prop="riskRemark" width="150" show-overflow-tooltip></el-table-column>
              <el-table-column align="center" label="家访资料" width="100">
                  <template scope="scope">
                      <span @click="openVisitPhoto(scope.row)" style="color: #20a0ff;text-decoration: underline;cursor: pointer;">查看</span>
                  </template>
              </el-table-column>
              <el-table-column  prop="visitRemark" align="center" label="家访说明" width="150" show-overflow-tooltip></el-table-column>
              <el-table-column  prop="visitUser" align="center" label="家访人员" width="150"></el-table-column>
              <el-table-column  prop="visitConfirmRemark" align="center" label="家访确认" width="140" show-overflow-tooltip></el-table-column>
              <el-table-column  prop="visitConfirmUser" align="center" label="确认人员" width="150"></el-table-column>
              <el-table-column align="center" label="签署人员" prop="protocolUser" width="150"></el-table-column>
              <el-table-column align="center" label="协议签署" width="150" fixed="right">
                  <template scope="scope">
                      <span v-if="scope.row.protocolStatus=== 0">未签署</span>
                      <el-button size="small" type="primary" v-else-if="scope.row.protocolStatus === 1" @click="openProtocolsDialog(scope.row)">查看协议</el-button>
                  </template>
              </el-table-column>
              <el-table-column align="center" label="手续费（元）" fixed="right" width="140">
                  <template scope="scope">
                      <el-button size="small" v-if="scope.row.auditStatus == '未核算'" @click="costAuditingTable(scope.row)">待核算</el-button>
                      <span style="color: #20a0ff;text-decoration: underline;cursor: pointer;" v-else-if="scope.row.auditStatus == '已核算'" @click="costAuditingTable(scope.row)">{{scope.row.feeAmount}}</span>
                  </template>
              </el-table-column>
              <el-table-column prop="auditor" align="center" label="核算人员" width="150"></el-table-column>
              <el-table-column align="center" label="操作" fixed="right" width="100">
                  <template scope="scope">
                      <el-button size="small" @click="returnLoan(scope.row)">退回</el-button>
                  </template>
              </el-table-column>
          </el-table>
      </div>

      <!--费用核算表-->
      <el-dialog title="费用核算表" :visible.sync="costAccountingDialog">
          <div class="costAccountingBox">
              <div class="costTableInpu">
                  <el-form :inline="true" :model="submitCostAccountingData" :rules="costAccountingRules" ref="searchItem" class="search-in">
                      <el-form-item label="核算时间" class="search-item" prop="auditTime">
                          <el-date-picker
                              v-model="submitCostAccountingData.auditTime"
                              type="datetime"
                              :editable="false"
                              placeholder="选择日期时间"
                              align="right"
                              :default-value="submitCostAccountingData.auditTime"
                          >
                          </el-date-picker>
                      </el-form-item>
                      <el-form-item label="核算人" class="search-item" prop="auditor">
                          <el-input :value="auditorInfo" :disabled="true" ></el-input>
                      </el-form-item>
                  </el-form>
              </div>
              <div class="costTableItme">
                  <table class="cost-table">
                      <tr>
                          <th width="60">序号</th>
                          <th>收费项目</th>
                          <th width="150">收费标准</th>
                          <th width="150">实收金额</th>
                          <th width="150">备注</th>
                      </tr>
                      <tr v-for="(item, index) in costAccountingData">
                          <td>{{index+1}}</td>
                          <td><span>{{item.feeName}}</span></td>
                          <td><span>{{item.feeAmount}}</span></td>
                          <td><el-input @change="costAccountingSumFn" v-model.number="item.fee" ref="number"></el-input></td>
                          <td><el-input v-model="item.remark"></el-input></td>
                      </tr>
                      <tr>
                          <td colspan="3">合计应收</td>
                          <td><span>{{costAccountingSum}}元</span></td>
                          <td>/</td>
                      </tr>
                  </table>
                  <div class="costAccountingBotton">
                      <el-button type="primary" @click="submitCostAccounTing" v-if="this.state == '未核算'">提交</el-button>
                      <el-button type="primary" @click="auditModifyPass" v-else-if="this.state == '已核算'">修改</el-button>
                      <el-button @click="costAccountingCancel">取消</el-button>
                  </div>
              </div>
          </div>
      </el-dialog>

      <!--查看协议-->
      <el-dialog title="协议" :visible.sync="protocolsDialog" class="Dialog">
          <el-carousel :autoplay="false" arrow="always" v-if="this.protocolsData.length>0" height="200px" indicator-position="outside" trigger="click">
              <el-carousel-item v-for="(item, index) in protocolsData" :key="index">
                  <img class="p-file" :src="item.protocolContent" alt="协议照片异常" @click="openBigPhoto(item.protocolContent)">
              </el-carousel-item>
          </el-carousel>
          <p v-else-if="this.protocolsData.length === 0" style="text-align: center;">暂无协议照片</p>
      </el-dialog>

      <!--家访照片-->
      <el-dialog title="家访照片" :visible.sync="visitPhotoDialog" class="Dialog">
          <el-carousel :autoplay="false" arrow="always" v-if="this.visitPhotoData.length>0" height="200px" indicator-position="outside" trigger="click">
              <el-carousel-item v-for="(item, index) in visitPhotoData" :key="index">
                  <img class="p-file" :src="item.url" alt="家访照片异常" @click="openBigPhoto(item.url)">
              </el-carousel-item>
          </el-carousel>
          <p v-else-if="this.visitPhotoData.length === 0" style="text-align: center;">暂无家访照片</p>
      </el-dialog>

      <!--分页-->
      <div class="page">
          <el-pagination
              :page-sizes="pageSizeArr"
              :total="pageTotal"
              layout="prev, pager, next, total, sizes"
              @current-change="loadDataPage"
              @size-change="loadDataPageSize"
              >
          </el-pagination>
      </div>

      <!--大图片预览-->
      <el-dialog v-model="dialogBigPhoto" class="dialogBigPhoto" size="full">
          <img :src="BigPhotoUrl" alt="" id="rotateIMG">
      </el-dialog>
  </div>
</template>

<script>
  import { listLoanAudit, loadCostAuditingData, auditCheck, auditModify, returnLoanCheck } from "@/api/api";
  export default {
      name: "finan",
      data () {
          let checkFee = (rule, value, callback) => {
              if (value < 0) {
                  callback(new Error('不能为负数'));
              } else {
                  callback();
              }
          };
          return {
              searchItem: {
                  userNo: "",
                  loanNo: "",
                  phone: "",
                  realName: "",
                  auditStatus: "",
                  pageNum: "1",
                  pageSize: "10"
              },
              tableData: [],
              pageSizeArr: ["10","30","50"],
              pageTotal: 0,
              // 费用核算表
              state: "",
              costAccountingDialog: false, // 弹窗
              productNoData: '',
              costAccountingData: [],
              costAccountingRules: {
                  auditTime: [
                      { type: 'date', required: true, message: '请输入核算时间', trigger: 'blur' }
                  ],
                  auditor: [
                      { required: true, message: '请输入核算人', trigger: 'blur' }
                  ],
                  fee: [
                      { validator: checkFee, trigger: 'change' }
                  ]
              },
              auditorInfo: "",
              submitCostAccountingData: {
                  auditTime: new Date(),
                  auditor: '',
                  loanNo: '',
                  fee: []
              },
              costAccountingSum: '',
              costAccountingSum2: '',
              // 查看协议；
              protocolsDialog: false,
              protocolsData: [],
              // 查看家访照片
              visitPhotoDialog: false,
              visitPhotoData: [],
              // 大图片预览
              dialogBigPhoto: false,
              BigPhotoUrl: ''
          };
      },
      methods: {
          // 重置
          resetForm () {
              this.$refs.searchItem.resetFields();
          },
          // 页码
          loadDataPage(page) {
              this.searchItem.pageNum = page;
              this.listLoanAudit();
          },
          // 页数
          loadDataPageSize(pageSize) {
              this.searchItem.pageSize = pageSize;
              this.searchItem.pageNum = 1;
              this.listLoanAudit();
          },
          // 列表查询；
          async listLoanAudit () {
              let _this = this;
              await listLoanAudit(
                  this.searchItem
              ).then(function(res) {
                  let Data = JSON.parse(res.data.ciphertext);
                  _this.pageTotal = Data.total;
                  Data = Data.list;
                  console.log(Data);
                  if (Data) {
                      for (let i=0; i<Data.length; i++) {
                          let DateUnit = ["年", "月", "日"];
                          let signRepayType = ["到期还款", "先息后本", "等额本息", "等额本金"];
                          let visitStatusType = ["未家访", "家访不通过", "确认不通过", "已确认"];
                          let auditStatusType = ["未核算", "已核算"];
                          // 状态
                          Data[i].auditStatus = auditStatusType[Data[i].auditStatus];
                          Data[i].visitStatus = visitStatusType[Data[i].visitStatus];

                          // 申请时间
                          if (Data[i].createTime) {
                              Data[i].createTime = _this.formatTime(Data[i].createTime);
                          }
                          // 面签时间
                          if (Data[i].signTime) {
                              Data[i].signTime = _this.formatTime(Data[i].signTime);
                          }
                          // 申请期限
                          if (Data[i].loanTime) {
                              if(Data[i].loanUnit === "0" || Data[i].loanUnit === "1" || Data[i].loanUnit === "2"){
                                  Data[i].loanTime = Data[i].loanTime + DateUnit[Data[i].loanUnit];
                              } else {
                                  Data[i].loanTime = Data[i].loanTime + Data[i].loanUnit;
                              }
                          };
                          // 借款期限
                          if (Data[i].signLoanTime) {
                              if (DateUnit[Data[i].signLoanUnit]) {
                                  Data[i].signLoanTime = Data[i].signLoanTime + DateUnit[Data[i].signLoanUnit];
                              }
                          }
                          // 还款方式
                          Data[i].signRepayType = signRepayType[Data[i].signRepayType];
                          // 风控初审时间
                          if (Data[i].riskTime) {
                              Data[i].riskTime = _this.formatTime(Data[i].riskTime);
                          }

                          // 风控初审借款期限
                          if (Data[i].riskLoanTime) {
                              if (Data[i].riskLoanUnit) {
                                  Data[i].riskLoanTime = Data[i].riskLoanTime + DateUnit[Data[i].riskLoanUnit];
                              }
                          }

                          // 风控初审还款方式
                          Data[i].riskRepayType = signRepayType[Data[i].riskRepayType];
                      };
                  }
                  _this.tableData = Data;
                  console.log(_this.tableData);
              });
          },
          // 打开费用核算表
          costAuditingTable (scope) {
              this.costAccountingDialog = true;
              this.loadCostAuditingData(scope.productNo, scope.loanNo);
              this.submitCostAccountingData.loanNo = scope.loanNo;
              this.submitCostAccountingData.auditTime = scope.auditTime;
              this.state = scope.auditStatus;
          },
          async loadCostAuditingData (productNo,loanNo) {
              let _this = this;
              loadCostAuditingData({
                  "productNo": productNo,
                  "loanNo": loanNo
              }).then((res) => {
                  let Data = JSON.parse(res.data.ciphertext);
                  _this.costAccountingData = Data;
                  this.costAccountingSumFn(); // 费用核算表金额总计
              });
          },
          // 费用核算表提交
          async submitCostAccounTing () {
              let _this = this;
              if(this.submitCostAccountingData.auditTime === undefined){
                  this.$message.error('核算时间不能为空！');
                  return false;
              }
              if (this.submitCostAccountingData.auditor === "") {
                  this.$message.error('核算人不能为空！');
                  return false;
              }
              for(let i = 0; i<this.costAccountingData.length; i++){
                  if (this.costAccountingData[i].fee < 0) {
                      this.$message.error('实收金额不能为负数');
                      return false;
                  }
                  if(this.costAccountingData[i].fee === ""){
                      this.costAccountingData[i].fee = 0;
                  }
              }
              for(let value of _this.costAccountingData){
                  _this.submitCostAccountingData.fee.push({
                      feeNo: value.feeNo,
                      feeAmount: value.fee,
                      remark: value.remark
                  });
              }
              await auditCheck(
                  _this.submitCostAccountingData
              ).then((res) => {
                  if(res.data.state.code === "200"){
                      _this.$message({
                          message: '成功',
                          type: 'success'
                      });
                      this.costAccountingCancel();
                      this.listLoanAudit();
                  }else{
                      this.$message.error(res.data.state.message);
                  }
              });
          },
          // 修改
          async auditModifyPass () {
              let _this = this;
              for(let value of this.costAccountingData){
                  if (value.fee < 0) {
                      this.$message.error('实收金额不能为负数');
                      return false;
                  }
                  if(value.fee === ""){
                      value.fee = 0;
                  }
                  this.submitCostAccountingData.fee.push({
                      feeNo: value.feeNo,
                      feeAmount: value.fee,
                      remark: value.remark
                  });
              }
              await auditModify(this.submitCostAccountingData).then((res) => {
                  if(res.data.state.code === "200"){
                      _this.$message({
                          message: '成功',
                          type: 'success'
                      });
                      this.costAccountingCancel();
                      this.listLoanAudit();
                  }else{
                      this.$message.error(res.data.state.message);
                  }
              });
          },
          // 费用核算表取消
          costAccountingCancel () {
              this.costAccountingDialog = false;
              this.submitCostAccountingData.auditTime = new Date();
              this.submitCostAccountingData.fee = [];
              this.costAccountingSum = ""; // 金额总计清除
          },
          // 费用核算表金额总计
          costAccountingSumFn () {
              this.costAccountingSum = "";
              for(let value of this.costAccountingData){
                  if (value.fee.length !== 0) {
                      if (typeof value.fee !== 'number') {
                          this.$message.error(value.feeName + '金额为数字');
                          return false;
                      }
                  }
                  if(value.fee){
                      this.costAccountingSum = Number(this.costAccountingSum) + Number(value.fee);
                  }
              }
          },
          // 查看家访照片：
          openVisitPhoto (rows) {
              this.visitPhotoDialog = true;
              this.visitPhotoData = rows.data;
          },
          // 查看协议：
          openProtocolsDialog (rows) {
              this.protocolsDialog = true;
              this.protocolsData = rows.protocols;
          },
          // 退回
          returnLoan (row) {
              let _this = this;
              this.$confirm('是否退回?', '提示', {
                  confirmButtonText: '是',
                  cancelButtonText: '否',
                  type: 'warning'
              }).then(() => {
                  returnLoanCheck({
                      "loanNo": row.loanNo
                  }).then((res) => {
                      if (res.data.state.code === "200") {
                          _this.$message({
                              message: "成功",
                              type: 'success'
                          });
                          _this.loadData();
                      } else {
                          _this.$message(res.data.state.message);
                      }
                  });
              }).catch(() => {
                  this.$message({
                      type: 'info',
                      message: '已取消'
                  });
              });
          },
          // 大图片预览
          openBigPhoto (item) {
              this.dialogBigPhoto = true;
              this.BigPhotoUrl = item;
          }
      },
      mounted: function () {
          this.$nextTick(function () {
              if (window.sessionStorage["sysUser"]) {
                  let userInfo = JSON.parse(window.sessionStorage.getItem("sysUser"));
                  this.auditorInfo = userInfo.name;
                  this.submitCostAccountingData.auditor = userInfo.userNo;
              } else {
                  this.$router.push({path: '/login'});
              }
              this.listLoanAudit();
          });
      },
      watch: {
          $route (to) {
              if(to.name === "financialAudit"){
                  this.listLoanAudit();
              }
          }
      }
  };
</script>

<style lang="scss">
  #finan{
      .interview-header{
          border: 1px solid #eee;
          margin:20px;
          padding:22px 0 0 20px;
          min-width: 1200px;
          box-sizing: border-box;
          .search-in{
              .search-item{
                  margin-right: 30px;
              }
          }
      }
      .table-box{
          border: 1px solid #eee;
          margin:20px;
          min-width: 1200px;
          .add-btn{
              margin: 20px;
              .el-icon-plus{
                  font-size:12px;
              }
          }
      }
      .page{
          text-align: right;
          padding:0 10px;
          .el-pagination{
              padding:0;
          }
      }
      .costAccountingTable{
          width: 800px;
          position: fixed;
          top: 20%;
          left: 50%;
          margin-left: -400px;
          background: #fff;
      }
      .costAccountingBox{
          margin: 0px auto;
          border-top: 1px solid #eee;
          h3{
              padding: 10px 0;
              text-align: center;
              border-bottom: 1px solid #eee;
          }
          .costTableInpu{
              text-align: center;
              padding: 20px 0;
          }
          .costTableItme{
              padding: 0 30px;
              table{
                  border-spacing:0;
                  width: 100%;
                  text-align: center;
                  th{
                      padding: 10px 0;
                      background: #f2f2f2;
                  }
                  th,td{
                      border: 1px solid #eee;
                  }
                  td{
                      height: 36px;
                      input{
                          text-align: center;
                          border: none;
                          outline: none;
                      }
                  }
              }
          }
          .costAccountingBotton{
              margin: 20px 0;
              text-align: center;
              button{
                  width: 180px;
                  margin: 0 30px;
              }
          }
      }
      .Dialog{
          img{
                max-width: 100%;
                max-height: 100%;
                display: block;
                margin: 0 auto;
                text-align: center;
          }
      }
      .dialogBigPhoto{
          img{
                max-width: 100%;
                max-height: 100%;
                display: block;
                margin: 0 auto;
                text-align: center;
          }
      }
   }
</style>
